<!doctype html><meta charset=utf-8>
<title> Shields.io Admin Monitoring Interface </title>
<style>
#monitorPlatform { display: none; }
</style>

<div id=passwordRequest>
  <p> Please enter your admin secret here:
  <input type=password id=secretInput>
</div>
<div id=monitorPlatform>
</div>

<script>
(function() {
  let network;
  const onLoad = function() {
    const secretInput = document.getElementById('secretInput');
    const onSecretChange = function() {
      const secret = secretInput.value;
      const authentication = `monitor:${secret}`;
      const headers = new Headers({
        Authorization: `Basic ${btoa(authentication)}`
      })
      fetch('/sys/network', {headers})
      .then(res => res.json())
      .then(networkData => {
        network = networkData;
        // Show monitor platform.
        monitorPlatform.style.display = 'block';
        passwordRequest.parentNode.removeChild(passwordRequest);

        // Show logs for each server.
        network.ips.forEach(ip => {
          const logger = document.createElement('div');
          const pre = document.createElement('pre');
          logger.textContent = ip;
          logger.appendChild(pre);
          monitorPlatform.appendChild(logger);

          // Set up the websocket.
          const setUpWebsocket = () => {
            const websocket = new WebSocket(
              (window.location.protocol === 'http:' ? 'ws' : 'wss') + '://' +
              ip + ':' + window.location.port + '/sys/logs');
            websocket.addEventListener('message', event => {
              pre.textContent += event.data + '\n';
            });
            websocket.addEventListener('close', () => {
              setTimeout(setUpWebsocket, 100);
            });
            websocket.addEventListener('open', () => {
              websocket.send(JSON.stringify({secret}));
            });
          };
          setUpWebsocket();
        });
      })
      .catch(alert)
    };
    secretInput.addEventListener('change', onSecretChange);
  };

  addEventListener('DOMContentLoaded', onLoad);
}());
</script>
